using System;
using System.Collections.Generic;
using System.Text;

namespace GuavaData
{
    public class Transaction : Object
    {
        #region Fields
        public String sqlTextResult;
        List<Command> contents;
        public List<Command> Contents
        {
            get { return contents; }
            set { contents = value; }
        }

        Dictionary<Command, IEnumerable<Command>> replace;
        #endregion Fields

        public Transaction()
        {
            contents = new List<Command>();
            replace = new Dictionary<Command, IEnumerable<Command>>();
        }

        public Transaction(Transaction t)
        {
            contents = new List<Command>(t.contents);
            replace = new Dictionary<Command, IEnumerable<Command>>();
        }

        public Transaction(IEnumerable<Command> commands)
        {
            contents = new List<Command>(commands);
            replace = new Dictionary<Command, IEnumerable<Command>>();
        }

        public Transaction(Operator o)
        {
            Command c = new Command(o);
            contents = new List<Command>();
            this.Add(c);
            replace = new Dictionary<Command, IEnumerable<Command>>();
        }

        public void Add(Command c)
        {
            c.container = this;
            contents.Add(c);
        }

        internal void NotifyChange(Command o, params Command[] onew)
        {
            replace.Add(o, onew);
        }

        internal void Complete()
        {
            // Go through the list of commands and replace the ones that need replacing
            List<Command> newlist = new List<Command>();
            foreach (Command c in this.contents)
            {
                if (replace.ContainsKey(c))
                    newlist.AddRange(replace[c]);
                else
                    newlist.Add(c);
            }

            foreach (Command c in newlist)
                c.container = this;

            contents = newlist;
        }

        public override string ToString()
        {
            String rv = "Transaction:\r\n";
            foreach (Command c in contents)
            {
                if (c.root is AddTable)
                    rv += ((AddTable)c.root).ToString();
                else if (c.root is ForeignKey)
                    rv += ((ForeignKey)c.root).ToString();
                else
                    rv += c.ToString();
                rv += "\r\n";
            }
            return rv;
        }
    }
}
